import logging

from bs4 import BeautifulSoup
from django.conf import settings

from forum.models import Comment, TopicFollow, TopicThumb, Topic, Attachments
from user_app.models import AccountInfo, AccountFollow, Role
from utils import query_utils
from utils.common_utils import json_response, Pagination
from utils.decorators import check_login, json_check
from utils.oss_utils import RunOSS

logger = logging.getLogger(__name__)
error_logger = logging.getLogger("error")


@check_login
def person_center_stat(request):
    # 个人中心，基础数据统计
    isFollow = False
    account_id = request.GET.get('account_id')
    if not account_id:
        account_id = request.session['account_id']
    if request.GET.get('account_id') != request.session['account_id']:
        # 如果进的是他人中心，查询是否关注
        isFollow = AccountFollow.objects.filter(follow_account_id=request.GET.get('account_id'), created_by_id=request.session['account_id']).exists()
    # 个人中心-成就数据统计
    topic_follow = TopicFollow.objects.filter(topic_account_id=account_id).count()
    topic_thumb = TopicThumb.objects.filter(topic_account_id=account_id).count()
    comment_count = Comment.objects.filter(created_by_id=account_id).count()
    # 个人关注，收藏统计
    my_topic_count = Topic.objects.filter(account_info=account_id).count()
    my_topic_follow = TopicFollow.objects.filter(created_by_id=account_id).count()
    my_account_follow = AccountFollow.objects.filter(created_by_id=account_id).count()
    my_fans = AccountFollow.objects.filter(follow_account_id=account_id).count()
    result_dict = {
        "topicFollow": topic_follow,
        "topicThumb": topic_thumb,
        "commentCount": comment_count,
        "myTopicCount": my_topic_count,
        "myTopicFollow": my_topic_follow,
        "myAccountFollow": my_account_follow,
        "myFans": my_fans,
        "isFollow": isFollow
    }
    return json_response({"code": 0, "message": "", "data": result_dict})


@check_login
def get_person_info(request):
    # 获取个人详细资料
    account_id = request.GET.get('account_id')
    if not account_id:
        account_id = request.session['account_id']

    try:
        ac = AccountInfo.objects.get(id=account_id)
        result_dict = {
            "id": ac.id,
            "nick_name": ac.nick_name,
            "mobile_phone": ac.mobile_phone,
            "avatar": ac.avatar,
            "slogan": ac.slogan,
            "sex": ac.sex,
            "location": ac.location,
            "qualifications": ac.qualifications,
            "province_code": ac.province_code,
            "city_code": ac.city_code,
            "role_name": Role.objects.get(id=ac.role_id).role_name,
        }
        return json_response({"code": 0, "message": "", "data": result_dict})
    except AccountInfo.DoesNotExist:
        return json_response({"code": 1000, "message": "account_id查询错误"})


@check_login
@json_check
def update_account_info(request, json_data: dict):
    account_id = request.session['account_id']
    nick_name = json_data.get("nick_name").strip()
    slogan = json_data.get("slogan")
    sex = json_data.get("sex")
    location = json_data.get("location", '')
    qualifications = json_data.get("qualifications", '')
    province_code = json_data.get("province_code", '')
    city_code = json_data.get("city_code")
    query = AccountInfo.objects.filter(nick_name=nick_name).exclude(id=account_id)
    if query:
        return json_response({"code": 1000, "message": "昵称已被占用"})
    ac = AccountInfo.objects.get(id=account_id)
    ac.nick_name = nick_name
    ac.slogan = slogan
    ac.sex = sex
    ac.location = location
    ac.qualifications = qualifications
    ac.province_code = province_code
    ac.city_code = city_code
    ac.save()
    return json_response({"code": 0, "message": "修改成功", "data": {}})


@check_login
def get_my_topic(request):
    # 获取个人的帖子信息
    account_id = request.GET.get('account_id')
    if not account_id:
        account_id = request.session['account_id']
    flag = request.GET.get('flag', "1")

    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    topic_count = Topic.objects.filter(account_info=account_id).count()
    p = Pagination(page=page, per_page=per_page, total=topic_count)
    query = Topic.objects.filter(account_info=account_id)
    if flag == '1':
        query = query.order_by("-created_on")
    elif flag == '2':
        query = query.order_by("-num_thumb")
    elif flag == '3':
        query = query.order_by("-num_replies")
    topic_list = query[p.offset:p.offset + per_page]
    result_list = []
    for item in topic_list:
        soup = BeautifulSoup(item.content, 'html.parser')
        parser_content = soup.get_text()
        tmp = {
            "id": item.id,
            "subject": item.subject,
            "content": parser_content,
            "numreplies": item.num_replies,
            "numthumb": item.num_thumb,
            "numviews": item.num_views,
            "is_simple": item.is_simple,
            "account": item.account_info.nick_name,
            "lastpost": item.last_post_account_id.nick_name if item.last_post_account_id else "",
            "lastreplyon": item.last_reply_on,
            "img_list": query_utils.get_img_attachments(item.id, category=0)
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@check_login
def get_my_follow_topic(request):
    # 获取收藏的帖子信息
    account_id = request.GET.get('account_id')
    if not account_id:
        account_id = request.session['account_id']

    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    follow_count = TopicFollow.objects.filter(created_by_id=account_id).count()
    p = Pagination(page=page, per_page=per_page, total=follow_count)
    follow_list = TopicFollow.objects.filter(created_by_id=account_id).order_by("-created_on").values_list("follow_topic_id", flat=True)[p.offset:p.offset + per_page]
    topic_list = Topic.objects.filter(id__in=list(follow_list))
    result_list = []
    for item in topic_list:
        soup = BeautifulSoup(item.content, 'html.parser')
        parser_content = soup.get_text()
        tmp = {
            "id": item.id,
            "subject": item.subject,
            "content": parser_content,
            "numreplies": item.num_replies,
            "numthumb": item.num_thumb,
            "numviews": item.num_views,
            "account_id": item.account_info.id,
            "account": item.account_info.nick_name,
            "avatar": item.account_info.avatar,
            "lastpost": item.last_post_account_id.nick_name if item.last_post_account_id else "",
            "lastreplyon": item.last_reply_on,
            "img_list": query_utils.get_img_attachments(item.id, category=0)
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@check_login
def get_my_follow_account(request):
    # 我的关注列表
    account_id = request.GET.get('account_id')
    if not account_id:
        account_id = request.session['account_id']

    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    follow_count = AccountFollow.objects.filter(created_by_id=account_id).count()
    p = Pagination(page=page, per_page=per_page, total=follow_count)
    follow_list = AccountFollow.objects.filter(created_by_id=account_id).values_list("follow_account_id", flat=True).order_by("-created_on")[p.offset:p.offset + per_page]
    account_list = AccountInfo.objects.filter(id__in=list(follow_list))
    result_list = []
    for item in account_list:
        tmp = {
            "id": item.id,
            "nick_name": item.nick_name,
            "mobile_phone": item.mobile_phone,
            "avatar": item.avatar,
            "slogan": item.slogan,
            "sex": item.sex,
            "qualifications": item.qualifications,
            "is_follow": AccountFollow.objects.filter(created_by_id=request.session['account_id'], follow_account_id=item.id).exists()
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@check_login
def get_my_fans_account(request):
    # 我的关注列表
    account_id = request.GET.get('account_id')
    if not account_id:
        account_id = request.session['account_id']

    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    follow_count = AccountFollow.objects.filter(follow_account_id=account_id).count()
    p = Pagination(page=page, per_page=per_page, total=follow_count)
    follow_list = AccountFollow.objects.filter(follow_account_id=account_id).values_list("created_by_id", flat=True).order_by("-created_on")[p.offset:p.offset + per_page]
    account_list = AccountInfo.objects.filter(id__in=list(follow_list))
    result_list = []
    for item in account_list:
        tmp = {
            "id": item.id,
            "nick_name": item.nick_name,
            "mobile_phone": item.mobile_phone,
            "avatar": item.avatar,
            "slogan": item.slogan,
            "sex": item.sex,
            "qualifications": item.qualifications,
            "is_follow": AccountFollow.objects.filter(created_by_id=request.session['account_id'], follow_account_id=item.id).exists()
        }
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@check_login
def change_avatar(request):
    # 更换头像接口
    try:
        account_id = request.session['account_id']
        file = request.FILES['file']
        filename = file.name
        oss = RunOSS(filename=filename, dirname=settings.OSS_UPLOAD_VOUCHER_DIR)
        ret = oss.uploadFIle(objectfile=file)
        # ret = {'status': 200, 'pay_certificate': 'http://u3dmodels.oss-cn-beijing.aliyuncs.com/voucher/202103041020485502.jpg', 'objectname': 'voucher/202103041020485502.jpg'}
        status = ret.get("status")
        if status == 200:
            file_url = ret['pay_certificate']

            result_dict = {
                "fileurl": file_url,
                "filename": filename
            }
            ac = AccountInfo.objects.get(id=account_id)
            ac.avatar = file_url
            ac.save()
            return json_response({"code": 0, "message": "更换成功", "data": result_dict})
        else:
            return json_response({"code": 1000, "message": "OSS传输失败"})
    except Exception as e:
        error_logger.exception("change_avatar have a  error ---->%s" % e.__str__())
        return json_response({"code": 4000, "message": "服务器内部错误"})
